import websocket from '../../utils/websocket';

Page({
  data: {
    groups: [],
    loading: false,
    unreadCounts: {} // 存储每个群组的未读消息数
  },

  onLoad() {
    this.loadGroups();
    this.setupWebSocket();
  },

  onShow() {
    // 页面显示时，标记当前不在任何群聊中
    wx.setStorageSync('currentGroupId', '');
  },

  onUnload() {
    websocket.close();
  },

  // 加载群组列表
  async loadGroups() {
    this.setData({ loading: true });
    try {
      const token = wx.getStorageSync('token');
      const response = await wx.request({
        url: 'http://your-server-address:8080/api/groups',
        method: 'GET',
        header: {
          'Authorization': `Bearer ${token}`
        }
      });

      if (response.statusCode === 200) {
        this.setData({
          groups: response.data
        });
      } else {
        wx.showToast({
          title: '获取群组列表失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('获取群组列表错误:', error);
      wx.showToast({
        title: '网络错误',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  // 设置WebSocket连接
  setupWebSocket() {
    const token = wx.getStorageSync('token');
    websocket.connect(token);

    // 注册消息处理器
    websocket.onMessage('GROUP_LIST_UPDATE', (data) => {
      this.setData({
        groups: data
      });
    });

    // 注册群聊消息处理器
    websocket.onMessage('GROUP_CHAT', (data) => {
      const currentGroupId = wx.getStorageSync('currentGroupId');
      if (currentGroupId === data.groupId) {
        // 如果在当前群聊中，直接发送到聊天界面
        const pages = getCurrentPages();
        const chatPage = pages.find(page => page.route === 'pages/group-chat/group-chat');
        if (chatPage) {
          chatPage.receiveMessage(data);
        }
      } else {
        // 如果不在当前群聊中，增加未读消息计数
        const unreadCounts = this.data.unreadCounts;
        unreadCounts[data.groupId] = (unreadCounts[data.groupId] || 0) + 1;
        this.setData({ unreadCounts });
      }
    });
  },

  // 进入群聊
  enterGroup(e) {
    const groupId = e.currentTarget.dataset.id;
    // 清除该群组的未读消息计数
    const unreadCounts = this.data.unreadCounts;
    unreadCounts[groupId] = 0;
    this.setData({ unreadCounts });
    
    // 设置当前群组ID
    wx.setStorageSync('currentGroupId', groupId);
    
    wx.navigateTo({
      url: `/pages/group-chat/group-chat?groupId=${groupId}`
    });
  }
}); 